<?php
namespace app\app\controller\v1;
use Think\Controller;
use think\Db;
use think\Request;
use app\app\util\OnlineUtils;
class ExchangeController extends BaseController{


    /**
     * @return array
     * [用户积分兑换卡]
     */
    public function changeCard()
    {
        $exchange['user_id'] = 1;                                                      //用户id
        $exchange['card_id'] = input('get.card_id');                                   //道具id
        $exchange['created_at'] = time();                                              //兑换时间
        $user_info = Db::name('user')->where('id','eq',$exchange['user_id'] )->find(); //用户信息
        $card_info = Db::name('card')->where('id','eq',$exchange['card_id'] )->find(); //卡片信息
        //如果用户的积分大于卡片所需的积分，才可进行兑换操作
        //兑换卡片，1.添加兑换记录，2.用户积分减少；3.用户的卡片数量加1;卡片的兑换数量加1
        if ( $user_info['integral'] >= $card_info['integral'] ) {
            DB::name('exchange')->insertGetId($exchange);             //添加兑换记录
            DB::query('update ft_user set integral = integral - '.$card_info["integral"].' where id ='.$exchange['user_id']);  //用户积分减少
            //my_card  是否有数据，有修改num，没有新增数据
            $my_card = Db::name('my_card')->where('user_id','eq',$exchange['user_id'])->where('card_id','eq',$exchange['card_id'])->find();
            if( $my_card ){
                DB::query('update ft_my_card set num = num + 1  where user_id ='.$exchange['user_id'].' and card_id ='.$exchange['card_id']);
            }else{
                Db::name('my_card')->insertGetId(['user_id'=>$exchange['user_id'],'card_id'=>$exchange['card_id'],'num'=>1]);
            }
            DB::query('update ft_card set exchange = exchange + 1  where id ='.$exchange['card_id']);   //卡片的兑换数量加1
            return ft(200,'兑换成功');
        }else{
            return ft(402,'用户积分不足兑换该卡');
        }


    }

}
